const api = require('../../utils/api.js');
const app = getApp();
Page({
  data: {
    goods_list: [],
    express_id: 0,
    star: [],
    disable: false,
    rider: 0,
    riderContent: '',
    imgUrl: app.imgUrl,
  },

  onLoad(opts) {
    let options = opts || {};
    app.pageOnLoad(this);
    let phone = wx.getSystemInfoSync();  //调用方法获取机型
    let phoneType;
    if (phone.platform == 'ios') {
      phoneType = true;
    } else if (phone.platform == 'android') {
      phoneType = false;
    }
    this.setData({
      order_id: options.id || '',
      entry: options.entry || '',
      express_id: opts.express_id || 0,
      opts: options,
      rider: Number(opts.riderid) > 0 ? 1 : 0,
      rider_id: options.riderid || 0,
      phoneType,
    });
    this.commentPreview();
  },

  commentPreview() {
    let that = this;
    let entry = that.data.entry;
    let url = '';
    if (entry) {
      if (entry === 'default') {
        url = api.order.comment_preview;
      } else if (entry === 'book') {
        url = api.book.comment_preview;
      } else if (entry === 'ms') {
        url = api.miaosha.comment_preview;
      } else if (entry === 'pt') {
        url = api.group.order.comment_preview;
      }
      wx.showLoading({
        title: '正在加载',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url,
        data: {
          order_id: that.data.order_id,
        },
        success: function(res) {
          wx.hideLoading();
          if (res.code === 1) {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success: function(e) {
                if (e.confirm) {
                  wx.navigateBack();
                }
              },
            });
          }
          if (res.code === 0) {
            for (let i in res.data.goods_list) {
              if ({}.hasOwnProperty.call(res.data.goods_list, i)) {
                res.data.goods_list[i].score = 3;
                res.data.goods_list[i].content = '';
                res.data.goods_list[i].pic_list = [];
                res.data.goods_list[i].uploaded_pic_list = [];
                res.data.goods_list[i].express_id = that.data.express_id;
              }
            }
            that.setData({
              goods_list: res.data.goods_list,
            });
          }
        },
      });
    } else {
      app.util.navigateTo('/ws_micro_shop/pages/user/user');
    }
  },

  sure() {
    let { star, rider, riderContent } = this.data;
    if (!rider) {
    if (this.writeAll() && Number(star.length) === 3) {
      this.setData({
        disable: true,
      });
    } else {
      this.setData({
        disable: false,
      });
    }
    } else {
      if (star[3] && riderContent) {
        this.setData({
          disable: true,
        });
      } else {
        this.setData({
          disable: false,
        });
      }
    }
  },

  writeAll() {
    let { goods_list } = this.data;
    return goods_list.every((item, index) => {
      return item.score && item.content;
    });
  },

  setScore(e) {
    let index = e.currentTarget.dataset.index;
    let score = e.currentTarget.dataset.score;
    let goods_list = this.data.goods_list;
    goods_list[index].score = score;
    this.setData({
      goods_list,
    });
    this.sure();
  },

  contentInput(e) {
    let { index, name } = e.currentTarget.dataset;
    if (name === 'goods') {
    this.data.goods_list[index].content = e.detail.value;
    this.setData({
      goods_list: this.data.goods_list,
    });
    } else {
      this.setData({
        riderContent: e.detail.value,
      })
    }
    this.sure();
  },

  chooseImage(e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let max_count = 6;
    let goods_list = that.data.goods_list;
    let current_count = goods_list[index].pic_list.length;
    wx.chooseImage({
      count: max_count - current_count,
      success: function(res) {
        goods_list[index].pic_list = goods_list[index].pic_list.concat(
          res.tempFilePaths
        );
        that.setData({
          goods_list,
        });
      },
    });
  },

  deleteImage(e) {
    let index = e.currentTarget.dataset.index;
    let pic_index = e.currentTarget.dataset.picIndex;
    let goods_list = this.data.goods_list;
    goods_list[index].pic_list.splice(pic_index, 1);
    this.setData({
      goods_list,
    });
  },

  commentSubmit() {
    if (
      !this.data.goods_list[0].score ||
      !this.data.goods_list[0].content ||
      Number(this.data.star.length) === 0
    ) {
      return console.log('over');
    }
    let that = this;
    wx.showLoading({
      title: '正在提交',
      mask: true,
    });
    let goods_list = that.data.goods_list;
    let siteinfo = app.siteInfo;
    let postData = {};
    let url = 'utility/file/upload';
    if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
      url = app.util.url(url, { type: 'image', thumb: '0' });
    }
    if (siteinfo && Number(siteinfo.uniacid) !== -1) {
      postData._uniacid = siteinfo.uniacid;
      postData._acid = siteinfo.acid;
    }
    uploadImages(0);
    function uploadImages(i) {
      if (i === goods_list.length) {
        return that.submit();
      }
      let complete_count = 0;
      let uploadFunc = j => {
        wx.uploadFile({
          url,
          name: 'file',
          formData: postData,
          filePath: goods_list[i].pic_list[j],
          complete: function(e) {
            let res = JSON.parse(e.data);
            if (res && res.url) {
              goods_list[i].uploaded_pic_list[j] = res.url;
            } else {
              wx.showToast({
                title: res.error.message + ',已被过滤' || '上传失败',
                icon: 'none',
              });
            }
            complete_count++;
            if (complete_count === goods_list[i].pic_list.length) {
              return uploadImages(i + 1);
            }
          },
        });
      };
      if (
        !goods_list[i].pic_list.length ||
        goods_list[i].pic_list.length === 0
      ) {
        return uploadImages(i + 1);
      }
      for (let j in goods_list[i].pic_list) {
        if (Object.prototype.hasOwnProperty.call(goods_list[i].pic_list, j)) {
          uploadFunc(j);
        }
      }
    }
  },

  submit() {
    let that = this;
    let { entry, rider, order_id, riderContent, star, goods_list, rider_id } = this.data;
      let url = '';
    let parm = {};
      if (entry === 'default') {
      if (!rider) {
        url = api.order.comment;
        parm = {
          order_id,
          goods_list: JSON.stringify(goods_list),
          star: JSON.stringify(star),
        }
      } else {
          url = api.rider.comment;
        parm = {
          order_id,
          content: riderContent,
          star_num: star[3],
          rider_id,
          id: '',
        }
        }
      } else if (entry === 'book') {
        url = api.book.submit_comment;
        parm = {
          order_id,
          goods_list: JSON.stringify(goods_list),
          star: JSON.stringify(star),
        }
      } else if (entry === 'ms') {
        url = api.miaosha.comment;
        parm = {
          order_id,
          goods_list: JSON.stringify(goods_list),
          star: JSON.stringify(star),
        }
      } else if (entry === 'pt') {
        url = api.group.order.comment;
        parm = {
          order_id,
          goods_list: JSON.stringify(goods_list),
          star: JSON.stringify(star),
        }
      }
      app.ws_micro_shoprequest({
        url,
        method: 'POST',
      data: parm,
        success: function(res) {
          wx.hideLoading();
          if (res.code === 0) {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              success: function(e) {
                if (e.confirm) {
                  // app.util.navigateTo('/ws_micro_shop/pages/order/order', { status: 3 }, true);

                  if (that.data.express_id) {
                    let pages = getCurrentPages(); //  获取页面栈
                    let prevPage = pages[pages.length - 2]; // 上一个页面
                    prevPage.change();
                  }

                  wx.navigateBack();
                }
              },
            });
          }
          if (res.code === 1) {
            wx.showToast({
              title: res.msg,
              icon: 'none',
            });
          }
        },
      });
  },

  collectFormId(e) {
    app.collectFormId(e);
  },

  star(e) {
    let index = e.currentTarget.dataset.index;
    let up = 'star[' + index + ']';
    this.setData({
      [up]: e.currentTarget.id,
    });
    this.sure();
  },

});
